
import dayjs from 'dayjs'
import serviceTools from '@/common/service';
import useService from '@/hooks/useService';
import { getDictList, getUserDictList } from "../../../RdsViews/components/RelatedName.js";
import { LowcodeOptions } from "../interface";
import type { LowcodeDisabled, LowcodeItemCFG, LowcodeMainService, LowcodePagePanelComponentItem, LowcodePageSearchItem } from "../interface";
import type { ComponentPropsHookProxy, ComponentPropsFunProxy } from "./interface";
import { cardInputComponentMap, lowcodeNumberToRuntimePrecision, LOWCODERUNTIMEUNIQUEKEY } from '../constant.js';
import { isLowcodeNumComponent } from '../utils.js';

const handleEditDisabled = (disabledConf: LowcodeDisabled) => {
  if (disabledConf?.type === "1") {
    return disabledConf?.value === "1";
  }
  return false;
};

const handleRangeEnum = async (mainService: LowcodeMainService, confObject?: LowcodePagePanelComponentItem) => {
  let rangEnum = [];  // { text: "", value: "" }[]
  const { c_itemCFG, c_guid } = (confObject || {});
  if (c_itemCFG && [LowcodeOptions.用户字典, LowcodeOptions.系统字典].includes(c_itemCFG?.optionType as any)) {
    rangEnum = c_itemCFG.optionType === LowcodeOptions.系统字典 ? getDictList(c_itemCFG.value) : getUserDictList(c_itemCFG.value);
    const excludeIds = c_itemCFG?.excludeValues ? c_itemCFG?.excludeValues?.split(",") : null;
    rangEnum = excludeIds ? rangEnum?.filter(d => !excludeIds.includes(d.c_id)) : rangEnum;
    rangEnum = rangEnum?.map(r => ({ text: r.c_name || r.c_id, value: r.c_id }));
  } else if (c_itemCFG && LowcodeOptions.自定义可选项 === c_itemCFG?.optionType && Array.isArray(c_itemCFG?.optionItems)) {
    rangEnum = c_itemCFG?.optionItems?.map(r => ({ text: r.title || r.value, value: r.value }));
  } else if (c_itemCFG && LowcodeOptions.自定义脚本 === c_itemCFG?.optionType) {
    const fetchParams = { ComponentGuid: c_guid, ComponentType: "2" };
    //  "2" 是因为 移动端 列表的Components，也是存在 Tbc_lowcode_component 表中，没存到tbc_lowcode_component_columns中
    // const fetchParams = { ComponentGuid: c_guid, ComponentType: parentSrc };
    const fetchRes = await mainService.request(LOWCODERUNTIMEUNIQUEKEY, "FetchDYSelectOptions", fetchParams);
    rangEnum = (fetchRes || [])?.map(r => ({ text: r.title, value: r.value }));;
    // rangEnum = await mainService.request('系统框架', 'CacheData', "objectData");
  }
  return rangEnum;
};

const textProps = async (mainService: LowcodeMainService, proxy?: ComponentPropsFunProxy) => {
  const { confObject: confObjectProp, dataObject, parentSrc = "2" } = proxy || {};
  const isComponent = confObjectProp && ("bindFieldDBType" in confObjectProp && "c_panel_guid" in confObjectProp); // isSearch;
  let confObject = confObjectProp, props = {};
  const { c_type, c_itemCFG, c_format, c_guid } = confObject || {};
  // c_valuetype 值类型->   1：字符串、2：整数、3：小数数值、4：日期、5：日期时间、6：时间
  const { c_valuetype, c_displayname_code } = (confObject || {}) as LowcodePagePanelComponentItem;
  const isNumVal = isLowcodeNumComponent({ c_type, c_valuetype });
  const rawDefVal = isNumVal ? "0" : "";

  // 属性 type
  props = { ...props, type: "name2" };

  // 属性 title
  if (confObject?.c_hide_title !== "1") {
    props = { ...props, title: confObject?.c_title || "" };
  }

  // 属性 titleStyle
  if (confObject?.c_hide_title !== "1") {
    // if (confObject?.c_title_width) {
    //   return { width: confObject.c_title_width + 'px' };
    // } // 不用设计的title宽度了
    props = { ...props, titleStyle: { "max-width": "180rpx", "text-overflow": "ellipsis", "white-space": "nowrap", overflow: "hidden" } };
  }

  // 属性 valueStyle
  let basicValueStyle: { [key: string]: string } = { "text-overflow": "ellipsis", "white-space": "nowrap", overflow: "hidden" };
  if (confObject?.c_hide_title !== "1") {
    if (isNumVal) {
      basicValueStyle = { ...basicValueStyle, "text-align": "right" };
    }
    props = { ...props, valueStyle: basicValueStyle };
  }

  // 属性 value
  const rawValue = dataObject?.[confObject?.c_code || ""] || rawDefVal;
  let basicValue = rawValue === 0 ? rawValue : (rawValue || "");
  const getDictStr = async () => { // 枚举和字典的转换
    if (c_itemCFG && [LowcodeOptions.用户字典, LowcodeOptions.系统字典].includes(c_itemCFG?.optionType as any)) {
      const rawDictEnum = c_itemCFG.optionType === LowcodeOptions.系统字典 ? getDictList(c_itemCFG.value) : getUserDictList(c_itemCFG.value);
      if (Array.isArray(rawDictEnum) && rawDictEnum.length) {
        // console.log("getComponentProps textProps dict ", c_itemCFG, rawDictEnum);
        const excludeIds = c_itemCFG?.excludeValues ? c_itemCFG?.excludeValues?.split(",") : null;
        const excludeDictEnum = excludeIds ? rawDictEnum?.filter(d => !excludeIds.includes(d.c_id)) : rawDictEnum;
        const valAry = (basicValue?.split(",") as string[])?.reduce((ary, v) => {
          const vDictItem = excludeDictEnum?.find(d => d.c_id === v);
          return vDictItem ? [...ary, vDictItem.c_name] : ary;
        }, [] as string[]);
        basicValue = valAry?.join(",");
      }
    } else if (c_itemCFG && LowcodeOptions.自定义可选项 === c_itemCFG?.optionType) {
      const customEnum = c_itemCFG?.optionItems;
      if (Array.isArray(customEnum) && customEnum.length) {
        const valAry = (basicValue?.split(",") as string[])?.reduce((ary, v) => {
          const vDictItem = customEnum?.find(d => d.value === v);
          return vDictItem ? [...ary, (vDictItem?.title || vDictItem?.value) as string] : ary;
        }, [] as string[]);
        basicValue = valAry?.join(",");
      }
    } else if (c_itemCFG && LowcodeOptions.自定义脚本 === c_itemCFG?.optionType) {
      const fetchParams = { ComponentGuid: c_guid, ComponentType: "2" };
      // const fetchParams = { ComponentGuid: c_guid, ComponentType: parentSrc };
      const fetchRes = await mainService.request(LOWCODERUNTIMEUNIQUEKEY, "FetchDYSelectOptions", fetchParams);
      const customEnum = fetchRes || [];
      // const customEnum = await mainService.request('系统框架', 'CacheData', "objectData");
      if (Array.isArray(customEnum) && customEnum.length) {
        const valAry = (basicValue?.split(",") as string[])?.reduce((ary, v) => {
          const vDictItem = customEnum?.find(d => d.value === v);
          return vDictItem ? [...ary, (vDictItem?.title || vDictItem?.value) as string] : ary;
        }, [] as string[]);
        basicValue = valAry?.join(",");
      }
    }
  };

  if (basicValue && c_displayname_code) {
    const basicValAry = basicValue.split(","), rawNameVal = dataObject?.[c_displayname_code] || "";
    basicValue = `[${basicValue}]${rawNameVal}`;
    if (basicValAry.length > 1 && typeof rawNameVal === "string" && rawNameVal?.length) {
      const nameValAry = rawNameVal.split(",");
      basicValue = basicValAry?.map((v: string, vIdx: number) => `[${v}]${nameValAry[vIdx] || ""}`)?.join(",");
    }
  } else if (basicValue && c_type && ["select", "radiogroup", "switch", "checkboxgroup", "checkbox"].includes(c_type) && c_itemCFG && c_itemCFG?.optionType) {
    await getDictStr();
  } else if (c_type === "numberinput" && c_format) {
    const dotCount = (lowcodeNumberToRuntimePrecision as any)[c_format];
    basicValue = (new Number(basicValue) || 0)?.toFixed(dotCount);
  } else if (["datetime", "time"]?.includes(c_type || "") && dayjs(basicValue).isValid() && c_format) {
    basicValue = dayjs(basicValue).format(c_format);
  }

  props = { ...props, value: basicValue };

  return props;
};

const cardInputProps = async (mainService: LowcodeMainService, proxy?: ComponentPropsFunProxy) => {
  const { confObject: confObjectProp, dataObject, parentSrc = "2" } = proxy || {};

  let confObject = confObjectProp;
  const { c_type, c_itemCFG, c_format, c_guid, c_input_method, c_displayname_code } = (confObject || {}) as LowcodePagePanelComponentItem;
  const carInputType = confObjectProp?.c_type ? cardInputComponentMap[confObjectProp.c_type] : "text";

  let props: { [key: string]: any } = {
    type: carInputType,
    // displayable c_disabled Obj
    required: confObject?.c_required === "1",
    // ...(confObject?.c_hide_title !== "1" ? { title: confObject?.c_title || "" } : {}),
    title: confObject?.c_title || "", // 即便是设置了隐藏标题，编辑时也应该展示出来
    placeholder: "",
  };

  if (c_input_method?.dialogCFG) {
    const mergeNameObj = c_displayname_code ? { name: dataObject[c_displayname_code] } : {};
    props = { ...props,  type: "textname", "right-icon-type": "right", ...mergeNameObj };
  }

  // 属性 disable
  if (confObject?.c_disabled && confObject?.c_disabled?.type) {
    props = { ...props, displayable: handleEditDisabled(confObject?.c_disabled) };
  }

  // 属性 placeholder
  if (!props?.displayable) {
    props = { ...props, placeholder: (confObject as LowcodePagePanelComponentItem)?.c_placeholder || `请录入${confObject?.c_title || ""}` };
  }

  if (["date"].includes(carInputType)) {
    props = { ...props, dateReturnType: c_format };
  }

  // 属性 range
  if (["selector", "radio", "multi"].includes(carInputType)) {
    const rangEnum = await handleRangeEnum(mainService, confObject as LowcodePagePanelComponentItem);
    props = { ...props, range: rangEnum };
  }

  return props;
};

const useComponentProps = (hookProxy?: ComponentPropsHookProxy) => {
  const mainService = useService({ prefix: "mainApi" });
  // const dict = serviceTools.getLocalStorage("rdsDict");
	// const ertert = getDictList('资材品类');
	// console.log("dict ==== ", dict, ertert);

  const getComponentProps = async (proxy?: ComponentPropsFunProxy) => {
    const { componentType: componentTypeProxy, confObject } = proxy || {};
    let componentType = componentTypeProxy || confObject?.c_type;

    let componentProps = {};

    switch(componentType) {
      case "textblock":
      case "EuiText":
        componentProps = await textProps(mainService, proxy);
        break
      default:
        componentProps = await cardInputProps(mainService, proxy);
        break;
    }

    return componentProps;
  };

  return { getComponentProps };
};

export default useComponentProps;


// EuiButton: typeof import('./components/button/button.vue')['default']
// EuiBacktop: typeof import('./components/backtop/backtop.vue')['default']
// EuiCardInput: typeof import('./components/cardinput/cardinput.vue')['default']
// EuiCheckbox: typeof import('./components/checkbox/checkbox.vue')['default']
// EuiConfigProvider: typeof import('./components/configprovider/configprovider.vue')['default']
// EuiIcon: typeof import('./components/icon/icon.vue')['default']
// EuiUIcons: typeof import('./components/uicons/uicons.vue')['default']
// EuiInput: typeof import('./components/input/input.vue')['default']
// EuiLazyList: typeof import('./components/lazylist/lazylist.vue')['default']
// EuiListTemplate: typeof import('./components/listtemplate/listtemplate.vue')['default']
// EuiNavBar: typeof import('./components/navbar/navbar.vue')['default']
// EuiPopup: typeof import('./components/popup/popup.vue')['default']
// EuiPopupApproval: typeof import('./components/popupapproval/popupapproval.vue')['default']
// EuiPopupDialog: typeof import('./components/popupdialog/popupdialog.vue')['default']
// EuiPopupMessage: typeof import('./components/popupmessage/popupmessage.vue')['default']
// EuiPopupShare: typeof import('./components/popupshare/popupshare.vue')['default']
// EuiSearchBar: typeof import('./components/searchbar/searchbar.vue')['default']
// EuiStatusBar: typeof import('./components/statusbar/statusbar.vue')['default']
// EuiTab: typeof import('./components/tab/tab.vue')['default']
// EuiText: typeof import('./components/text/text.vue')['default']
// EuiVirtualList: typeof import('./components/virtuallist/virtuallist.vue')['default']
// EuiSegmentedControl: typeof import('./components/segmentedcontrol/segmentedcontrol.vue')['default']



// "text", "multitext", "dialoginput", "numberinput", "buttongroup", "radiogroup",
// "checkbox", "checkboxgroup", "datetime", "daterange", "time", "select", "richtext",
// "textblock", "fileupload", "imageupload", "status", "switch"